package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {


    // 动态获取存放文件基路径
    @Value("${itheima.basepath}")
    private String basePath;

    /**
     *
     * @param file file是一个临时保存的文件，需要转存
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info(file.toString());

        // 查看目录是否存在，
        File basefile = new File(basePath);
        if(!basefile.exists()) {
            basefile.mkdirs();
        }

        // 获取源文件名称，并获取文件后缀
        String name = file.getOriginalFilename();
        String suffix = name.substring(name.lastIndexOf("."));

        // 使用UUID自动生成文件名，避免文件名称重复
        String fileName = UUID.randomUUID().toString() + suffix;

        // 将file临时文件转存为永久文件
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        // 通过输入流读取文件
        FileInputStream fileInputStream = null;
        // 通过输出流将文件输出到前端页面
        ServletOutputStream servletOutputStream = null;
        try {
            fileInputStream = new FileInputStream(basePath + name);
            servletOutputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            byte[] bytes = new byte[1024];
            int len = 0;
            while((len = fileInputStream.read(bytes)) != -1) {
                servletOutputStream.write(bytes, 0, len);
                servletOutputStream.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
